import { Picker as PickerView } from "@tarojs/components";
import { useEffect, useState } from "react";
import { AtList, AtListItem } from "taro-ui";

type PickerOption = {
  options: any[]
  value: any
  onChange?: (value: any) => void
  valueKey?: string
  labelKey?: string
  filterMethod?: (item: any) => boolean
  title?: string
  className?: string
  noteKey?: string
}

function Picker(props: PickerOption) {
  const {
    onChange,
    options,
    value,
    valueKey = 'id',
    labelKey = 'name',
    filterMethod,
    title,
    className,
    noteKey,
  } = props
  const [selectedIndex, setSelectedIndex] = useState<number>()
  // 已过滤的选项
  const [filteredOptions, setFilteredOptions] = useState<any[]>([])
  const handleChangeValue = (e) => {
    const index = e.detail.value
    const selectValue = filteredOptions[index]?.[valueKey]
    onChange && onChange(selectValue)
  }

  useEffect(() => {
    // 如果有 filterMethod，则过滤已存在的选项（当前 value 值要保留），否则直接使用 options
    if (filterMethod) {
      const _options = options.filter((item) => {
        if (item[valueKey] === value) {
          return true
        }
        return filterMethod(item)
      })
      setFilteredOptions(_options)
    } else {
      setFilteredOptions(options)
    }
  }, [options, filterMethod, valueKey, value])

  useEffect(() => {
    const index = filteredOptions.findIndex(item => item[valueKey] === value)
    setSelectedIndex(index)
  }, [value, filteredOptions, valueKey])

  const selectValueLabel = selectedIndex !== undefined ? filteredOptions[selectedIndex]?.name : ''

  const fieldTitle = title || selectValueLabel
  const extraText = title ? (selectValueLabel || '请选择') : selectValueLabel ? '' : '请选择'
  const node = (noteKey && selectedIndex !== undefined) ? filteredOptions[selectedIndex]?.[noteKey] : undefined

  return (
    <PickerView
      className={className}
      mode='selector'
      range={filteredOptions}
      rangeKey={labelKey}
      onChange={handleChangeValue}
      value={selectedIndex}
    >
      <AtList hasBorder={false}>
        <AtListItem
          title={fieldTitle}
          extraText={extraText}
          note={node}
          arrow='right'
        />
      </AtList>
    </PickerView>
  );
}

export { Picker };
